package com.wangxiang.sys.manage.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;

import com.google.code.kaptcha.Producer;
import com.wangxiang.common.utils.R;
import com.wangxiang.sys.manage.dao.RoleUserDao;
import com.wangxiang.sys.manage.entity.LoginEntity;


import com.wangxiang.sys.manage.entity.LoginLogEntity;
import com.wangxiang.sys.manage.service.*;

import com.wangxiang.sys.manage.utils.RedisUtils;
import com.wangxiang.sys.manage.utils.SysAuthUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
@RequestMapping("/sys")
public class LoginController {
    @Resource
    Producer producer;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    LoginService loginService;
    @Resource
    private LoginLogService loginLogService;
    @Autowired
    private RoleUserDao roleUserDao;
    @Autowired
    private UserService userService;
    @Autowired
    private LoginLogGatewayService logs;




    @RequestMapping("/login")
    public R sysLogin(@RequestBody LoginEntity form){
        /**
         * 由于之前版本代码效率低，导致后端延迟，前端超时
         * 简单优化一下
         * 原因找到，主要是服务器带宽不够，数据访问慢导致数据超时，主从切换，本地数据库为主，服务器为从
         */

        String uuid = redisUtils.get("uuid").toString();
        String captcha = redisUtils.get("captchacode").toString();
        //验证码过期校验
        if (uuid.equals(null) | form.getUuid().equals(null)){
            return R.error("验证码过期，请刷新");
        }
        //验证码错误校验
        if(form.getUuid().equals(uuid) && !form.getCaptcha().equals(captcha)){
            return R.error("验证码错误");
        }

        //用户名密码校验
        LoginEntity DBform = loginService.login(form.getLoginId());
        if (DBform == null || !form.getPassword().equals(DBform.getPassword())){
            return R.error("用户名或密码错误");
        }
        String login = "登录";
        //日志系统
//        loginService.addLog(DBform.getUserId(),login);

        //新版登录日志
       logs.addLogs(DBform.getUserId(), 0);



        /**
         * 重构返回角色id,
         */
        int roleId= roleUserDao.getRoleIdByUser(DBform.getUserId());
//        System.out.println("权限id"+roleId);
        if (roleId==0){
            return R.error("权限过期，请联系王相，18485546913");
        }


        return R.ok().put("roleId",roleId).put("userId",DBform.getUserId());
    }
    @RequestMapping("/captcha")
    public R getCaptcha() throws IOException {
        //生成UUD,UUID结构位2f15d99a-2ace-466e-b207-9cb6301e8855的一串字符
        String uuid = UUID.randomUUID().toString();
        //生成一个5位随机数,使用hutool工具
        String captchaCode = RandomUtil.randomString(5);
//        String captchaCode = "诚是傻逼";
        //字符转换成图片
        BufferedImage image = producer.createImage(captchaCode);
        //流操作，返回值为bool
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image,"jpeg",byteArrayOutputStream);

        //把图片转换为base64为编码
        BASE64Encoder encoder = new BASE64Encoder();
        String header = "data:image/jpeg;base64,"; //前缀
        String base64Img = header + encoder.encode(byteArrayOutputStream.toByteArray());
        //把验证码存到redis
        redisUtils.set("uuid",uuid);
        redisUtils.set("captchacode",captchaCode);
        return R.ok().put("uuid",uuid).put("captcha",base64Img);
    }

    /**
     * 退出登录
     */
    @RequestMapping("/loginOut")
    public R loginOut(@RequestBody LoginEntity login){
        if (login.getUserId()==0){
            return R.error("你还未登录");
        }
//        String status = "登出";
//        loginService.addLog(login.getUserId(),status);
        userService.lineStatus(login.getUserId(),0);
        logs.addLogs(login.getUserId(), 1);
        return R.ok().put("msg","你已退出系统").put("code",700);
    }




}
